package cn.edu.scau.cmi.ema.service;

import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import java.util.*;
@Service("PurchasematerialService")
@Transactional

public class PurchasematerialServiceImpl extends CmiEmaService implements PurchasematerialService {
	public PurchasematerialServiceImpl() {
	}

	@Transactional
	public Purchasematerial savePurchasematerial(Purchasematerial purchasematerial) {

		if (purchasematerial.getId() == null) {
			Material material = materialDAO.findMaterialById(purchasematerial.getMaterial().getId());
			Producer producer = producerDAO.findProducerById(purchasematerial.getProducer().getId());
			Supplier supplier = supplierDAO.findSupplierById(purchasematerial.getSupplier().getId());
			Unit unit = unitDAO.findUnitById(purchasematerial.getUnit().getId());

			Purchasematerial existingPurchasematerial = purchasematerialDAO.findPurchasematerialByPhysicalPrimaryKey(
					producer.getId(), supplier.getId(), material.getId(), purchasematerial.getDate());

			purchasematerial.setMaterial(material);
			purchasematerial.setProducer(producer);
			purchasematerial.setSupplier(supplier);
			purchasematerial.setUnit(unit);

			if (isEquals(purchasematerial, existingPurchasematerial)) {
				return existingPurchasematerial;
			}

			purchasematerial = purchasematerialDAO.store(purchasematerial);
			purchasematerialDAO.flush();

		} else {
			Purchasematerial existingPurchasematerial = purchasematerialDAO
					.findPurchasematerialByPrimaryKey(purchasematerial.getId());

			purchasematerial = purchasematerialDAO.store(purchasematerial);
			purchasematerialDAO.flush();
		}

		return purchasematerial;
	}

	public void deletePurchasematerial(Purchasematerial purchasematerial) {
		purchasematerialDAO.remove(purchasematerial);
		purchasematerialDAO.flush();
	}

	@Transactional
	public void deletePurchasematerials(Set<Integer> deletePurchasematerialsId) {
		Query query = purchasematerialDAO.createNamedQuery("deletePurchasematerialsById", -1, -1);
		query.setParameter(1, deletePurchasematerialsId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Purchasematerial> loadPurchasematerials() {
		return purchasematerialDAO.findAllPurchasematerials();

	}

	@Transactional
	public Set<Purchasematerial> loadReferencePurchasematerials(Set<Purchasematerial> purchasematerials) {
		Iterator<Purchasematerial> purchasematerialsIterator = purchasematerials.iterator();
		Set<Purchasematerial> referencedPurchasematerials = new HashSet<>();
		while (purchasematerialsIterator.hasNext()) {
			Purchasematerial currentPurchasematerial = purchasematerialsIterator.next();

		}
		return referencedPurchasematerials;
	}

	public Set<Purchasematerial> loadPurchasematerialsByIdSet(Set<Integer> purchasematerialIdSet) {

		Iterator<Integer> purchasematerialIdIterator = purchasematerialIdSet.iterator();
		Set<Purchasematerial> purchasematerialSet = new HashSet<>();
		while (purchasematerialIdIterator.hasNext()) {
			Integer id = purchasematerialIdIterator.next();
			Purchasematerial currentPurchasematerial = purchasematerialDAO.findPurchasematerialById(id);
			purchasematerialSet.add(currentPurchasematerial);
		}
		return purchasematerialSet;
	}

	@Transactional
	public List<Purchasematerial> findAllPurchasematerials(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Purchasematerial>(
				purchasematerialDAO.findAllPurchasematerials(startResult, maxRows));
	}

	@Transactional
	public Purchasematerial findPurchasematerialByPrimaryKey(Integer id) {
		return purchasematerialDAO.findPurchasematerialByPrimaryKey(id);
	}

	@Transactional
	public Integer countPurchasematerials() {
		return ((Long) purchasematerialDAO.createQuerySingleResult("select count(o) from Purchasematerial o")
				.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countPurchasematerials(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Purchasematerial.class);
		return ((Long) purchasematerialDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 *
	 */
	@Transactional
	public Integer countPurchasematerialsByName(String queryName) {
		Query query = purchasematerialDAO.createNamedQuery("countPurchasematerialsByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countPurchasematerialsByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Purchasematerial.class);
		Session session = (Session) entityManager.getDelegate();
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadPurchasematerialObjectReferencedSet(Purchasematerial purchasematerial) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();
		if (purchasematerial.getMaterial() != null) {

			Set<Integer> materialIds = new HashSet<Integer>();
			materialIds.add(purchasematerial.getMaterial().getId());
			objectReferencedSetMap.put("materialIds", materialIds);
		}
		if (purchasematerial.getProducer() != null) {

			Set<Integer> producerIds = new HashSet<Integer>();
			producerIds.add(purchasematerial.getProducer().getId());
			objectReferencedSetMap.put("producerIds", producerIds);
		}
		if (purchasematerial.getSupplier() != null) {

			Set<Integer> supplierIds = new HashSet<Integer>();
			supplierIds.add(purchasematerial.getSupplier().getId());
			objectReferencedSetMap.put("supplierIds", supplierIds);
		}
		if (purchasematerial.getUnit() != null) {

			Set<Integer> unitIds = new HashSet<Integer>();
			unitIds.add(purchasematerial.getUnit().getId());
			objectReferencedSetMap.put("unitIds", unitIds);
		}

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadPurchasematerialClassReferencedSet(Purchasematerial purchasematerial) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("materials", materialDAO.findAllMaterials());
		classReferencedSetMap.put("producers", producerDAO.findAllProducers());
		classReferencedSetMap.put("suppliers", supplierDAO.findAllSuppliers());
		classReferencedSetMap.put("units", unitDAO.findAllUnits());

		return classReferencedSetMap;
	}

	public boolean isEquals(Purchasematerial purchasematerial, Object obj) {
		if (obj == purchasematerial)
			return true;
		if (!(obj instanceof Purchasematerial))
			return false;
		Purchasematerial comparedPurchasematerial = (Purchasematerial) obj;
		if (!CheckPropertyEqual(purchasematerial.getProducer().getId(),
				comparedPurchasematerial.getProducer().getId())) {
			return false;
		}
		if (!CheckPropertyEqual(purchasematerial.getSupplier().getId(),
				comparedPurchasematerial.getSupplier().getId())) {
			return false;
		}
		if (!CheckPropertyEqual(purchasematerial.getMaterial().getId(),
				comparedPurchasematerial.getMaterial().getId())) {
			return false;
		}
		if (!CheckPropertyEqual(purchasematerial.getDate(), comparedPurchasematerial.getDate())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

